<template>
  <ex-dialog
    width="900px"
    class="ex-diolog"
    :title="title"
    :visible="visible"
    @closeDialog="handleClose"
  >	
		<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm" :disabled="disabled">
      <el-form-item label="标题" prop="title">
				<el-input type="text" v-model="ruleForm.title" autocomplete="off" placeholder="请输入标题"></el-input>
			</el-form-item>
      <el-form-item label="通知模板" prop="templateId">
         <el-select v-model="ruleForm.templateId" placeholder="请选择" size="small" @change="changeTemplate">
            <el-option v-for="item in templateList" :key="item.id" :label="item.templateName" :value="item.id">
            </el-option>
          </el-select>
			</el-form-item> 
       <el-form-item label="" v-if="content" >
         <div class="templateText">{{content}}</div>
			</el-form-item>
      <div class="listBox" v-if="ruleForm.textField.length > 0">
        <div class="lable">自定义字段</div>
        <div class="rigBox"  >
          <el-form-item 
            :label="`字段${index+1}`" 
            v-for="(item,index) in ruleForm.textField" 
            :key="index" 
            label-width="60px" 
            :prop="'textField.'+index + '.text'" 
            :rules="rules.text">
            <el-input type="text" v-model="item.text" autocomplete="off" ></el-input>
			    </el-form-item>
        </div>
      </div>
          
			<el-form-item label="通知用户" >
          <el-upload class="upload-demo" :action="fileaction" :headers="headers" :data="fileData" :limit="1" 
            :on-success="handleFileChange" :show-file-list="true" :file-list="fileList">
            <el-button type="primary" size="small">导入用户</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
      </el-form-item>  
      <el-row>
        <el-col :span="14">
          <el-form-item label="用户手机号" >
            <el-input type="text" v-model="ruleForm.phone" autocomplete="off" placeholder="请输入手机号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-button type="primary" style="margin-left: 20px" @click="addPhone">添加</el-button>
          <el-button type="primary" @click="handleSend('ruleForm')" :loading="subLoading">发送短信</el-button>
        </el-col>
      </el-row>
      <div style="margin-bottom: 20px">
        <ex-table ref="table" :loading="loading" :table-column="tableColumn" :table-data="ruleForm.phoneList" :showPage="true">
          
          <template v-slot:status="{ scope }">
            <div style="color: #1890ff;">{{scope.row.status}}</div>
          </template>
          <template v-slot:operate="{ scope }">
            <el-button @click="deletePhone(scope.row.id)" size="small">删除</el-button>
          </template>
        </ex-table>
      </div>
			<el-form-item>
				<el-button type="primary" @click="submitForm('ruleForm')" :loading="subLoading">保存草稿</el-button>
			</el-form-item>
		</el-form>
  </ex-dialog>
</template>
<script>
// components
import Loading from '@/components/Loading/index'
import {
  getToken
} from "@/utils/auth";
// api
  import {
    addMessage,
    messageTemplate,
    getCustomer,
    textmessageDetail,
    editTextmessage,
    postTextMessage,
  } from "@/api/smsConfiguration";

export default {
  components: {
    Loading
  },
  props: {
    visible: Boolean,
    pathType: String,
    id: String,
  },
  data() {
    
    return {
      title: '新增短信通知',
      fileData: {
        id: '',
      },
      fileList: [],
      fileaction: process.env.VUE_APP_BASE_API + "/text/message/v1/customer/import",
      headers: {
        "X-Access-Token": getToken(),
      }, //设置上传文件请求头
      imgLoading: false,
      subLoading: false,
			ruleForm: {
				id: '',
        params: '',//参数数组
        textField: [

        ],  
        phoneList: [],//参数数组
        templateId: '',//模版id
        title: '',//短信通知标题
        phone: '',
      },
      content: '',
      paramCount: 0,
      
			rules: {
        title: [
          { required: true,message: '请输入标题',trigger: 'blur' }
        ],
        templateId: [
          { required: true,message: '请选择模板', trigger: 'change' }
        ],
        text:  [
          { required: true,message: '输入自定义字段',trigger: 'blur' }
        ],
      },
      loading: false,
      templateList: [],
      disabled: false,
      tableColumn: [{
            prop: "name",
            label: "用户姓名"
          },
          {
            prop: "phone",
            label: "手机号",
          },
          {
            label: "操作",
            slot: true,
            slotName: "operate",
            fixed: "right",
            width: 100
          },
        ],
    }
  },
  computed: {
   
  },
  created() {
    this.ruleForm.activityId = this.id
    this.getmessageTemplate()
    if(this.pathType == 'edit'){
      this.title = '编辑短信通知'
      this.getDetail()
    }else if(this.pathType == 'detail'){
      this.title = '查看短信通知'
      
      this.getDetail()
      this.disabled = true
    }
     console.log('this.tableColumn',this.tableColumn)
  },
  mounted(){
    if(this.pathType == 'detail'){
        this.tableColumn.pop()
        var obj = {
          label: "通知结果",
          slot: true,
          slotName: "status",
          fixed: "right",
          width: 120
        }
        this.tableColumn.push(obj)
       
    }
   
  },
  methods: {
    //获取短信详情
    getDetail(){
      textmessageDetail(this.id).then(res => {
        // this.ruleForm = res.result
        this.ruleForm.id = res.result.id
        this.ruleForm.params = res.result.params
          
        this.ruleForm.phoneList = res.result.phoneList//参数数组
        this.ruleForm.templateId = res.result.templateId//模版id
        this.ruleForm.title = res.result.title//短信通知标题
        this.content = res.result.content
        console.log('res.result.paramList',res.result.paramList)
        res.result.paramList.forEach(item => {
          var obj = {}
          obj.text = item
          this.ruleForm.textField.push(obj)
        })
      })
    },
    //获取短信模板
    getmessageTemplate(){
      messageTemplate().then(res => {
        this.templateList = res.result
        console.log('res',res)
      })
    },
    //获取模板
    changeTemplate(e){
      this.ruleForm.textField = []
      this.templateList.forEach(item =>{
        if(item.id == e){
          this.content = item.content
          this.paramCount = item.paramCount
         
          for(var i = 0;i<this.paramCount;i++){
            var obj = {
              text: '',
            }
            console.log('i',i)
            this.ruleForm.textField.push(obj)
          }
          console.log('this.ruleForm.textField',this.ruleForm.textField)
        }
      })
    },
    //导入文件
    handleFileChange(res, file) {
      console.log('文件', res, file)
      if (res.code == 200) {
        this.$message.success('导入成功');
        this.ruleForm.phoneList = res.result
      } else {
        this.$message.error(res.message);
        
      }
    },
    //添加手机号
    addPhone(){
      var data = {
        phone: this.ruleForm.phone
      }
      getCustomer(data).then(res => {
        if(res.code == 200){
          this.ruleForm.phoneList.push(res.result)
          this.ruleForm.phone = ''

        }
      })
    },
    /* 删除手机号码 */
    deletePhone(id){
        this.$confirm("是否删除？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            this.ruleForm.phoneList.forEach((item,index) => {
              if(item.id == id ){
                this.ruleForm.phoneList.splice(index,1)
              }
            })
          })
          .catch(() => {

          });
    },
    //新建子账号
    submitForm(formName) {
      console.log('formName',formName)
      this.$refs[formName].validate((valid) => {
        this.subLoading = false
        if (valid) {
          var params = []
          this.ruleForm.textField.forEach(item => {
            params.push(item.text)
          })
          this.ruleForm.params = params.join()  
          var data = {
            id: this.ruleForm.id,
            params: this.ruleForm.params,
            phoneList: this.ruleForm.phoneList,
            templateId: this.ruleForm.templateId,
            title: this.ruleForm.title
          }
          if(this.pathType == 'add'){
           
            addMessage(data).then(res => {
              this.handleSuccess("创建成功")
              this.subLoading = false
            }).finally(() => {
              this.subLoading = false
            })
          }else if(this.pathType == 'edit'){
           
            editTextmessage(data).then(res => {
              this.handleSuccess("编辑成功")
            }).finally(() => {
              this.subLoading = false
            })
          }
         
             
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    
		//取消
    handleClose(formName) {
      this.$emit('update:visible', false)
			// this.$refs[formName].resetFields();
    },
		//确认
		handleConfirm(){
			this.$emit('success', '你好')
		},
    handleSuccess(msg) {
      if (msg === '已拒绝') {
        var type = 'error'
      } else {
        var type = 'success'
      }
      this.$message({
        message: msg,
        type: type,
        duration: 1500,
        onClose: () => {
          this.handleClose()
          this.$emit('success')
        }
      })
    },
    //发送短信
    handleSend(formName){
       this.$refs[formName].validate((valid) => {
         
        if (valid) {
          this.subLoading = true
          var params = []
          this.ruleForm.textField.forEach(item => {
            params.push(item.text)
          })
          this.ruleForm.params = params.join()  
          var data = {
            id: this.ruleForm.id,
            params: this.ruleForm.params,
            phoneList: this.ruleForm.phoneList,
            templateId: this.ruleForm.templateId,
            title: this.ruleForm.title
          }
          postTextMessage(data).then(res => {
            this.handleSuccess("开始发送短信")
            this.subLoading = false
          }).finally(() => {
            this.subLoading = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
		padding: 0 !important;
  }
	::v-deep .ex--dialog--main {
    padding: 10px 20px !important;
  }
}
::v-deep .avatar-uploader2 .el-upload {
  width: 100% !important;
}
.el-radio-group{
  display: flex;
  justify-content: flex-start;
}
.el-radio{
  display: flex;
  justify-content: flex-start;
  ::v-deep .el-radio__input{
    margin-top: 14px;
  }
  
}

.smsBox{
  display: flex;
  flex-direction: column;
  .content{
    padding: 14px 20px;
    border: 1px solid #DCDFE6;
    border-radius: 8px;
  }
  .name{
    margin-top: 20px;
  }
}
.listBox{
  display: flex;
  justify-content: flex-start;
  .lable{
    width: 140px;
    text-align: right;
    height: 36px;
    line-height: 36px;
    vertical-align: middle;
    font-size: 14px;
    color: #606266;
  }
  .el-input{
    width: 550px;
  }
}
.templateText{
  border: 1px solid #DCDFE6;
  padding: 14px;
  border-radius: 14px;
  width: 380px;
  line-height: 1.6;
}
</style>